package org.luxor.cloud.authentication.service.impl;


import org.luxor.cloud.authentication.service.IUserDetailsFeign;
import org.luxor.commons.core.web.data.R;
import org.luxor.commons.security.entity.UserSubject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用于Security框架,加载登陆者用户数据的核心接口
 *
 * @author yanxinming
 */
@Primary
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private IUserDetailsFeign userDetailsFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        R<UserSubject> userSubject = userDetailsFeign.loadUserByUsername(username);
        if (userSubject.isSuccess()) {
            return userSubject.getData();
        }
        logger.error("根据登陆账号获取详情信息，失败！code:[{}] message:[{}]", userSubject.getCode(), userSubject.getMessage());
        throw new UsernameNotFoundException(userSubject.getMessage());
    }
}
